import { _decorator, Component, Node, Button, director } from 'cc';
import { GameManager } from '../core/GameManager';
import { BoardManager } from '../core/BoardManager';
import { Timer } from '../components/Timer';
import { ScoreDisplay } from '../components/ScoreDisplay';
import { GameOverPanel } from '../components/GameOverPanel';

const { ccclass, property } = _decorator;

/**
 * 游戏主场景
 * 负责管理游戏场景的初始化和游戏流程控制
 */
@ccclass('GameScene')
export class GameScene extends Component {
    @property(Node)
    private boardNode: Node = null;
    
    @property(Node)
    private uiNode: Node = null;
    
    @property(Node)
    private pausePanel: Node = null;
    
    @property(Button)
    private pauseButton: Button = null;
    
    @property(Button)
    private resumeButton: Button = null;
    
    @property(Button)
    private restartButton: Button = null;
    
    @property(Button)
    private menuButton: Button = null;
    
    @property(GameManager)
    private gameManager: GameManager = null;
    
    private _timer: Timer = null;
    private _scoreDisplay: ScoreDisplay = null;
    private _gameOverPanel: GameOverPanel = null;
    private _isPaused: boolean = false;
    
    // 生命周期函数
    onLoad() {
        // 查找GameManager组件
        this.findGameManager();
        
        // 检查GameManager是否存在
        if (!this.gameManager) {
            console.error("游戏管理器未找到，请确保场景中有GameManager节点");
            return;
        }
        
        // 初始化棋盘管理器
        const boardManager = this.boardNode?.getComponent(BoardManager);
        if (!boardManager) {
            console.error("棋盘管理器未初始化");
            return;
        }
        
        // 获取组件引用
        this._timer = this.getComponentInChildren(Timer);
        this._scoreDisplay = this.getComponentInChildren(ScoreDisplay);
        this._gameOverPanel = this.getComponentInChildren(GameOverPanel);
        
        // 注册按钮事件
        if (this.pauseButton) {
            this.pauseButton.node.on(Button.EventType.CLICK, this.onPauseGame, this);
        }
        
        if (this.resumeButton) {
            this.resumeButton.node.on(Button.EventType.CLICK, this.onResumeGame, this);
        }
        
        if (this.restartButton) {
            this.restartButton.node.on(Button.EventType.CLICK, this.onRestartGame, this);
        }
        
        if (this.menuButton) {
            this.menuButton.node.on(Button.EventType.CLICK, this.onBackToMenu, this);
        }
        
        // 初始化面板
        if (this.pausePanel) {
            this.pausePanel.active = false;
        }
        
        if (this._gameOverPanel) {
            this._gameOverPanel.node.active = false;
        }
    }
    
    /**
     * 查找GameManager实例
     */
    private findGameManager(): void {
        if (!this.gameManager) {
            // 尝试在场景中查找GameManager
            const gameManagerNode = director.getScene().getChildByName('GameManager');
            if (gameManagerNode) {
                this.gameManager = gameManagerNode.getComponent(GameManager);
            }
            
            if (!this.gameManager) {
                console.warn('未找到GameManager引用，某些功能可能无法正常工作');
            }
        }
    }
    
    start() {
        // 开始游戏
        this.startGame();
    }
    
    onDestroy() {
        // 移除事件监听，先检查对象和节点是否有效
        if (this.pauseButton && this.pauseButton.isValid && this.pauseButton.node && this.pauseButton.node.isValid) {
            this.pauseButton.node.off(Button.EventType.CLICK, this.onPauseGame, this);
        }
        
        if (this.resumeButton && this.resumeButton.isValid && this.resumeButton.node && this.resumeButton.node.isValid) {
            this.resumeButton.node.off(Button.EventType.CLICK, this.onResumeGame, this);
        }
        
        if (this.restartButton && this.restartButton.isValid && this.restartButton.node && this.restartButton.node.isValid) {
            this.restartButton.node.off(Button.EventType.CLICK, this.onRestartGame, this);
        }
        
        if (this.menuButton && this.menuButton.isValid && this.menuButton.node && this.menuButton.node.isValid) {
            this.menuButton.node.off(Button.EventType.CLICK, this.onBackToMenu, this);
        }
    }
    
    /**
     * 开始游戏
     */
    private startGame(): void {
        // 确保GameManager存在
        if (!this.gameManager) {
            console.error("找不到GameManager实例，无法开始游戏");
            return;
        }
        
        // 重置游戏状态
        this.gameManager.resetGame();
        
        // 重置分数显示
        if (this._scoreDisplay) {
            this._scoreDisplay.resetScore();
        }
        
        // 重置计时器
        if (this._timer) {
            this._timer.resetTimer();
            this._timer.startTimer();
        }
        
        // 初始化棋盘
        const boardManager = this.boardNode?.getComponent(BoardManager);
        if (boardManager) {
            boardManager.initBoard();
        }
        
        // 隐藏面板
        if (this.pausePanel) {
            this.pausePanel.active = false;
        }
        
        if (this._gameOverPanel) {
            this._gameOverPanel.hide();
        }
        
        this._isPaused = false;
    }
    
    /**
     * 暂停游戏
     */
    private onPauseGame(): void {
        if (this._isPaused) return;
        
        this._isPaused = true;
        
        // 暂停游戏逻辑
        if (this.gameManager) {
            this.gameManager.pauseGame();
        }
        
        // 暂停计时器
        if (this._timer) {
            this._timer.pauseTimer();
        }
        
        // 显示暂停面板
        if (this.pausePanel) {
            this.pausePanel.active = true;
        }
    }
    
    /**
     * 恢复游戏
     */
    private onResumeGame(): void {
        if (!this._isPaused) return;
        
        this._isPaused = false;
        
        // 恢复游戏逻辑
        if (this.gameManager) {
            this.gameManager.resumeGame();
        }
        
        // 恢复计时器
        if (this._timer) {
            this._timer.resumeTimer();
        }
        
        // 隐藏暂停面板
        if (this.pausePanel) {
            this.pausePanel.active = false;
        }
    }
    
    /**
     * 重新开始游戏
     */
    private onRestartGame(): void {
        // 停止当前所有计时和动画
        this.unscheduleAllCallbacks();
        
        // 重置游戏状态
        if (this.gameManager) {
            this.gameManager.restartGame();
        }
        
        // 确保UI重置
        this._isPaused = false;
        if (this.pausePanel) {
            this.pausePanel.active = false;
        }
        
        if (this._gameOverPanel) {
            this._gameOverPanel.hide();
        }
        
        // 重置分数显示
        if (this._scoreDisplay) {
            this._scoreDisplay.resetScore();
        }
        
        // 重置并启动计时器
        if (this._timer) {
            this._timer.resetTimer();
            this._timer.startTimer();
        }
        
        // 获取并重置棋盘
        const boardManager = this.boardNode?.getComponent(BoardManager);
        if (boardManager) {
            boardManager.initBoard();
        }
        
        console.log("游戏已重新开始");
    }
    
    /**
     * 返回主菜单
     */
    private onBackToMenu(): void {
        // 加载主菜单场景
        director.loadScene('MainMenu', (err) => {
            if (err) {
                console.error('加载主菜单失败:', err);
            } else {
                console.log('成功加载主菜单');
            }
        });
    }
    
    /**
     * 游戏结束
     */
    public onGameOver(): void {
        // 设置游戏结束状态
        if (this.gameManager) {
            this.gameManager.endGame();
        }
        
        // 停止计时器
        if (this._timer) {
            this._timer.stopTimer();
        }
        
        // 显示游戏结束面板
        if (this._gameOverPanel) {
            this._gameOverPanel.show();
        }
    }
} 